<?php
namespace Admin\Controller;
use Think\Exception;

/**
 * 角色相关控制器
 * Class RoleController
 * @package Admin\Controller
 */
class RoleController extends AbstractController {
    /**
     * 角色列表
     */
    public function index(){
        $keyword = I('keyword');
        if(!empty($keyword)){
            $where['Name'] = array('like','%'.$keyword.'%');
        }
        $where['IsDel'] = array('neq','1');

        $count = M('Role')->where($where)->count();
        $page = $this->page($count, 1);
        $fields = 'r.*';
        $list = M('Role as r')->where($where)->field($fields)->limit($page->firstRow . ',' . $page->listRows)->select();

        $this->assign('list',$list);
        $this->assign("page", $page->show('Admin'));
        $this->display();
    }

    /**
     * 添加角色
     */
    public function add(){
        if(IS_POST){
            $data = $_POST;
            try{
                $result = M('Role')->add($data);
                if($result){
                    $this->success('添加成功');
                }else{
                    $this->error('添加失败');
                }
            } catch (Exception $exception){
                $this->error($exception->getMessage());
            }
        }else{
            $this->display();
        }
    }

    /**
     * 编辑角色
     */
    public function edit(){
        if(IS_POST){
            try{
                $data = $_POST;
                $result = M('Role')->save($data);
                if($result){
                    $this->success('编辑成功！');
                }else{
                    $this->error('编辑失败！');
                }
            }catch(Exception $exception){
                $this->error($exception->getMessage());
            }
        }else{
            $id = I('id');
            $role = M('Role')->find($id);
            $this->assign('role',$role);
            $this->display();
        }
    }

    /**
     * 删除角色
     */
    public function delete(){
        $id = I('id');
        try{
            $count = M('Role_user_rel')->where(array('RoleID' => $id))->count();
            if($count > 0){
                throw new Exception('该角色下还有用户，不能删除!');
            }
            $role = M('Role')->find($id);
            $role['IsDel'] = 1;
            $result = M('Role')->save($role);
            if($result){
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        } catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }
}